﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using QLHD.Models;
using QLHD.WS;
using System.Globalization;
using QLHD.Utilities;

namespace QLHD
{
    public partial class Report : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //bpa/1NsGnDU=
            if (Session["TKBC"] == null || Session["TKBC"].ToString() != "1")
            {
                return;
            }
            if (IsPostBack)
                return;

            Session["viewonly"] = false;
            List<PhongBan> viewphongbanids = new AuthenticationHelper().GetListPhongban();
            //List<PhongBan> viewphongbanids = new QLHD2013Entities().PhongBans.Where(q => q.TrangThai == true).ToList();
            var pbs = ((from item in viewphongbanids
                        select new
                        {
                            ID = item.ID,
                            Ten = item.Ten
                        })).ToList();

            chklphongban.DataSource = pbs;
            chklphongban.DataBind();

            btnExpExcel.Enabled = false;
        }

        private void BindReport()
        {
            QLHD2013Entities db = new QLHD2013Entities();
            List<hd> lst = new List<hd>();
            string fromd = txtfromdate.Text;
            string tod = txttodate.Text;
            //int departmentid = int.Parse(drphongban.SelectedValue);
            string trangthai = chktrangthai.SelectedValue;

            List<HopDong> lsthopdong;
            int total = 0;
            List<int> slroomid = new List<int>();

            foreach (ListItem item1 in chklphongban.Items)
            {
                if (item1.Selected == true)
                {
                    slroomid.Add(int.Parse(item1.Value));
                }
            }

            hdservice ut = new hdservice();
            List<int> viewphongbanids = ut.GetViewDepartmentIDs();

            DateTime fromdate = DateTime.Parse("01/01/1901 00:00:00");
            DateTime todate = DateTime.Parse("09/09/2099 23:59:59");
            var provider = new CultureInfo("vi-VN");
            if (!string.IsNullOrEmpty(fromd))
                fromdate = Convert.ToDateTime(fromd + " 00:00:00", provider);

            if (!string.IsNullOrEmpty(tod))
                todate = Convert.ToDateTime(tod + " 23:59:59", provider);

            lsthopdong = db.HopDongs.Where(q =>
                q.TrangThaiHD == 1
                && (q.ParentID == null || q.ParentID == 0)
                    //&& q.DepartmentID == departmentid
                && q.NgayTaoHD >= fromdate && q.NgayTaoHD <= todate
                && q.DepartmentID != null
                ).ToList();

            DateTime today = DateTime.Today;
            today = new DateTime(today.Year, today.Month, today.Day, 0, 0, 0);

            lsthopdong.RemoveAll(q => q.DepartmentID != null && (!viewphongbanids.Contains((int)q.DepartmentID)));
            lsthopdong.RemoveAll(q => q.DepartmentID != null && (!slroomid.Contains((int)q.DepartmentID)));
            //trang thai
            if (trangthai == "done")
            {
                lsthopdong.RemoveAll(q => q.NgayThanhLyHD == null || q.GiaTriThanhLyHD == null || q.GiaTriThanhLyHD <= 0);
            }
            else if (trangthai == "doing")
            {
                lsthopdong.RemoveAll(q => q.NgayThanhLyHD != null || q.GiaTriThanhLyHD > 0);
            }

            total = lsthopdong.Count();
            lsthopdong = lsthopdong.OrderBy(q => q.NgayTaoHD).ToList();

            DateTime now = DateTime.Now;
            List<hd> source = new List<hd>();
            int i = 1;
            int num = 1;
            foreach (HopDong item in lsthopdong)
            {
                var _hd = GetHDModel(item, i.ToString());
                _hd.STT = i.ToString();
                source.Add(_hd);//hop dong chinh
                string tail = ".1";
                num = 1;
                //phu luc hop dong
                var plhdchinh = GetChildren(item, 0, i.ToString(), out num);
                if (plhdchinh.Count() > 0)
                {
                    source.Add(new hd() { STT = i + tail, TenHD = "Phụ lục hợp đồng chính" });
                    source.AddRange(plhdchinh);
                    tail = ".2";
                }
                var xnklhdchinh = GetXNKL(item);
                if (xnklhdchinh.Count() > 0)
                {
                    source.Add(new hd() { STT = i + tail, TenHD = "Xác nhận khối lượng HĐ chính" });
                    source.AddRange(xnklhdchinh);
                    tail = ".3";
                }

                var hdtn = item.HopDong1.Where(q => q.ParentID == item.MaHD && q.TrangThaiHD==1 && q.TypeID == 1).ToList();
                if (hdtn.Count() > 0)
                {
                    //hop dong thue ngoai
                    source.Add(new hd() { STT = i + tail, TenHD = "Hợp đồng thuê mua ngoài" });
                    int j = 1;
                    foreach (HopDong tn in hdtn)
                    {
                        var _tn = GetHDModel(tn, i + tail + "." + j.ToString());
                        source.Add(_tn);//hop dong chinh
                        string tail1 = "a";
                        //phu luc hop dong
                        var plhdtn = GetChildren(tn, 0, j.ToString(), out num);
                        if (plhdtn.Count() > 0)
                        {
                            source.Add(new hd() { STT = tail1, TenHD = "Phụ lục hợp đồng thuê ngoài" });
                            source.AddRange(plhdtn);
                            tail1 = "b";
                        }
                        var xnklhdtn = GetXNKL(tn);
                        if (xnklhdtn.Count() > 0)
                        {
                            source.Add(new hd() { STT = tail1, TenHD = "Xác nhận khối lượng HĐ thuê ngoài" });
                            source.AddRange(xnklhdtn);
                        }
                        j++;
                    }
                }
                i++;
            }

            Repeater1.DataSource = source;
            Repeater1.DataBind();

            if (source.Count() > 0)
                btnExpExcel.Enabled = true;
        }
        private static List<hd> GetChildren(HopDong root, int contracttype, string firstnumber, out int num, int startnum = 1)
        {
            List<hd> child = new List<hd>();
            num = 0;
            if (root.HopDong1 == null && root.HopDong1.Where(q => q.TrangThaiHD == 1 && q.TypeID == contracttype).Count() == 0)
                return child;
            int i = 0;
            int j = 0;
            foreach (HopDong item in root.HopDong1.Where(q => q.TrangThaiHD == 1 && q.TypeID == contracttype))
            {
                child.Add(GetHDModel(item, ""));
                child.AddRange(GetChildren(item, contracttype, "", out j));
                i++;
            }
            num = i;
            return child;
        }
        private static hd GetHDModel(HopDong item, string firstnumber)
        {
            return new hd()
            {
                STT = firstnumber,
                MaHD = item.MaHD.ToString(),
                TenHD = item.TenHD,
                SoHD = item.SoHD,
                MaDoiTac = item.MaDoiTac != null ? item.MaDoiTac.ToString() : "",
                TenDoiTac = (item.DoiTac != null) ? item.DoiTac.TenDoiTac : "",
                GiaTriHD = item.GiaTriHD != null ? ((decimal)item.GiaTriHD).ToString("N", CultureInfo.CreateSpecificCulture("en-US")) : "",
                ThoiGianNopBaoCao = item.ThoiGianNopBaoCao != null ? ((DateTime)item.ThoiGianNopBaoCao).ToString("dd/MM/yyyy") : "",
                TienDoThucHien = item.TienDoThucHien,
                GhiChu = item.GhiChu,
                ChuNhiemCongTrinh = item.ChuNhiemCongTrinh,
                NgayThanhLyHD = item.NgayThanhLyHD != null ? ((DateTime)item.NgayThanhLyHD).ToString("dd/MM/yyyy") : "",
                GiaTriThanhLyHD = item.GiaTriThanhLyHD != null ? ((decimal)item.GiaTriThanhLyHD).ToString("N", CultureInfo.CreateSpecificCulture("en-US")) : "",
                ParentID = item.ParentID != null ? item.ParentID.ToString() : "",
                NgayTaoHD = item.NgayTaoHD != null ? ((DateTime)item.NgayTaoHD).ToString("dd/MM/yyyy") : "",
                DepartmentID = item.DepartmentID != null ? item.DepartmentID.ToString() : "0",
                CanhBaoTruoc = item.CanhBaoTruoc != null ? item.CanhBaoTruoc.ToString() : "",
                DepartmentName = item.PhongBan != null ? item.PhongBan.Ten : ""
            };
        }

        private List<hd> GetXNKL(HopDong hd)
        {
            var s = (from item in hd.XNKLs.ToList()
                     select new hd
                     {
                         TenHD = item.NoiDung,
                         GhiChu = item.GhiChu,
                         XNKLNgay = item.NgayXNKL.ToString("dd/MM/yyyy"),
                         XNKLGiaTri = item.GiaTri != null ? ((decimal)item.GiaTri).ToString("N", CultureInfo.CreateSpecificCulture("en-US")) : "",
                         HoaDonSo = item.SoHoaDon,
                         HoaDonNgay = item.NgayXNKL.ToString("dd/MM/yyyy")
                     }).ToList();
            return s;
        }

        protected void btnShow_Click(object sender, EventArgs e)
        {
            BindReport();
        }

        protected void btnExpExcel_Click(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;
            string filename = "Thong ke hop dong - " + DateTime.Today.ToString("dd-MM-yyyy") + ".xls";
            Response.AddHeader("content-disposition", "attachment;filename=" + filename);
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";

            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            //     Your Repeater Name Mine is "Rep"
            Repeater1.RenderControl(htmlWrite);
            Response.Write("<table>");
            Response.Write(stringWrite.ToString());
            Response.Write("</table>");
            Response.End();
        }

        public int GetColspan(string group)
        {
            int colspan = 0;
            switch (group.ToLower())
            {
                case "hopdong":
                    colspan += chkdoitac.Checked ? 1 : 0;
                    colspan += chksodh.Checked ? 1 : 0;
                    colspan += chkngaykyhd.Checked ? 1 : 0;
                    colspan += chkgiatrihd.Checked ? 1 : 0;
                    colspan += chkthoigianth.Checked ? 1 : 0;
                    colspan += chkghichuhd.Checked ? 1 : 0;
                    break;
                case "xnkl":
                    colspan += chkxnklgiatri.Checked ? 1 : 0;
                    colspan += chkxnklngay.Checked ? 1 : 0;
                    break;
                case "thanhly":
                    colspan += chkngaythanhly.Checked ? 1 : 0;
                    colspan += chkgiatrithanhly.Checked ? 1 : 0;
                    break;
                case "hoadon":
                    colspan += chksohoadon.Checked ? 1 : 0;
                    colspan += chkngayhoadon.Checked ? 1 : 0;
                    break;
                case "tutt":
                    colspan += chkngaytutt.Checked ? 1 : 0;
                    colspan += chkgiatritutt.Checked ? 1 : 0;
                    break;
            }
            return colspan;
        }
    }
}